from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)


@app.route('/api/v2/token', methods=['post'])
def get_token():
    url = "http://api.cimidata.com/api/v2/token"
    req_data = json.loads(request.get_data())
    app_id = req_data.get('app_id')
    app_secret = req_data.get('app_secret')
    data = {
        'app_id': app_id,
        'app_secret': app_secret
    }
    res_json = requests.post(url=url, json=data).json()
    return jsonify(res_json)


@app.route('/api/v2/accounts', methods=['post'])
def sub_wechat():
    access_token = request.args["access_token"]
    url = "http://api.cimidata.com/api/v2/accounts?access_token=" + access_token
    req_data = json.loads(request.get_data())
    accounts = req_data.get('accounts')
    data = {
        'accounts': accounts
    }
    res_json = requests.post(url=url, json=data).json()
    return jsonify(res_json)


@app.route('/api/v2/account/<account_id>/articles', methods=['get'])
def get_account_latest_articles(account_id):
    access_token = request.args["access_token"]
    idx = request.args.get("idx") or None
    last_id = request.args.get("last_id") or None
    params = {
        "access_token": access_token,
        "idx": idx,
        "last_id": last_id
    }

    url = "http://api.cimidata.com/api/v2/account/" + account_id + "/articles"
    res_json = requests.get(url=url, params=params).json()
    return jsonify(res_json)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)
